package com.qingyun.customview.dragview

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.Scroller

class MyScrollerDragView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {
    private val mScroller = Scroller(context)

    override fun computeScroll() {
        super.computeScroll()
        if (mScroller.computeScrollOffset()) {
            val currX = mScroller.currX
            val currY = mScroller.currY
            (parent as? View)?.scrollTo(currX, currY)
            invalidate()
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_UP -> {
                val view = parent as? View ?: return false
                mScroller.startScroll(
                    view.scrollX,
                    view.scrollY,
                    -view.scrollX,
                    -view.scrollY
                )
                invalidate()
            }

        }
        return true
    }
}
